package com.wichatbackapi.controller;


import com.wf.captcha.ArithmeticCaptcha;
import com.wichatbackapi.domain.doa.SysUser;
import com.wichatbackapi.redis.RedisCache;
import com.wichatbackapi.result.AjaxResult;
import com.wichatbackapi.result.ResponseResult;
import com.wichatbackapi.service.LoginServcie;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Tag(name="登录接口")
@RestController
public class LoginController {
    @Autowired
    private LoginServcie loginServcie;
    @Autowired
    private RedisCache redisCache;
    @Operation(summary = "登录")
    @PostMapping("/login")//用户登录
    public ResponseResult login(@RequestBody SysUser sysUser){
        System.out.println("传过来的用户信息"+ sysUser);
        return loginServcie.login(sysUser);
    }
    @Operation(
            summary = "注册",
            description = "账号注册",
            parameters = {
                    @Parameter(name = "userName", description = "账号", required = true),
                    @Parameter(name = "password", description = "密码", required = true)
            },
            responses = {
                    @ApiResponse(responseCode = "200", description = "成功登录，返回 JWT 令牌"),
                    @ApiResponse(responseCode = "401", description = "用户名或密码错误"),
                    @ApiResponse(responseCode = "500", description = "服务器内部错误")
            }
    )
    @PostMapping("/register")//用户注册
    public ResponseResult register(@RequestBody SysUser sysUser){
        return loginServcie.register(sysUser);
    }
    @Operation(summary = "获取验证码")
    @GetMapping("/getCheckCode")
   public AjaxResult getCheckCode(){
        ArithmeticCaptcha captcha = new ArithmeticCaptcha(120, 40);
        String text = captcha.text();
        String base64 = captcha.toBase64();
        HashMap<String, String> dataMap = new HashMap<>();
        // 生成UUID
        String uuid = UUID.randomUUID().toString();
        // 返回验证码标识
        dataMap.put("code",uuid);
        // 返回验证码结果
        dataMap.put("result",text);
        // 返回验证码base64图片
        dataMap.put("base64",base64);
        String redisKey = "checkCode:"+uuid;
        // 将验证码存入redis中(缓存60秒）
        redisCache.setCacheObject(redisKey,uuid,60, TimeUnit.SECONDS);
        return AjaxResult.success(dataMap);
   }

}
